//
//  NewsViewController.m
//  xpkc
//
//  Created by TopSage iOS on 14/12/18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "NewsViewController.h"
#import "NewsContentViewController.h"
#import "MJRefresh.h"
#import "NewsHeaderView.h"
#import "NewsTypeViewController.h"
#import "MBProgressHUD.h"

#define AdHeight 150


#define new 0

@interface NewsViewController ()
{
    UIScrollView *_adScrollView;// ???
    
    //类别，下载的
    NSMutableArray *columnArray;
    
    UIButton *_btn; // ???
    //把button放到数组里
    //    NSMutableArray *_btnArray;
    //底部大scrollView
    UIScrollView *_scrollView;
    //标题
    UIScrollView *columnScroll;
    //栏目第二页偏移量
    
    NSInteger _secondPage; // ???
    
    //本地
    NSMutableArray *columnsShow;
    NSMutableArray *columnsHide;
    NSMutableArray *columnsAll;
    //新闻数据
    NSMutableArray *newsData;
    int pages[100];
    
    
}
@end

//总共图片数量
#define kIMGCOUNT 4

@implementation NewsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"首页";
        self.tabBarItem.title = @"首页";
        self.tabBarItem.image =[UIImage imageNamed:@"tab_home"];
        if (IsIOS7) {
            //iOS7颜色的渲染问题
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_home_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    newsData = [NSMutableArray array];
    
    // 创建顶部标题scrollView，同时从本地数据中拿到顶部标题，如果本地没有就从服务器请求并存入本地
    [self creatColumnScroll];
    
    // 创建新闻底部scrollView
    [self creatScrollView];
    
    // 请求顶部标题数据，如果拿到大于等于一条数据就请求下面新闻数据
    [self requestNewsColumns];
    
    //单击手势   什么作用？？
    //    UITapGestureRecognizer *taptop = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tabToTop)];
    //
    //    [self.navigationController.navigationBar addGestureRecognizer:taptop];
}

- (void)creatNavigationItem{
    //取消返回钮
    
}
/**
 *   顶部分类
 */
-(void)creatColumnScroll{
    
    columnScroll =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, 40)];
    columnScroll.showsHorizontalScrollIndicator = NO;
    columnScroll.showsVerticalScrollIndicator = NO;
    columnScroll.backgroundColor = RGBCOLOR(246, 246, 246);
    columnScroll.contentSize = CGSizeMake(SCREEN_WIDTH, 40);
    columnScroll.delegate = self;
    [self.view addSubview:columnScroll];
    
    
    
    //展示的数据
    columnsShow= [NSMutableArray arrayWithContentsOfFile:COMMONLYCOLUMN_PATH];
    // NSLog(@"%@",COMMONLYCOLUMN_PATH);
    //隐藏的数据
    columnsHide = [NSMutableArray arrayWithContentsOfFile:OTHERCOLUMN_PATH];
    //    NSLog(@"%@",OTHERCOLUMN_PATH);
    //所有的数据
    columnsAll = [[NSMutableArray alloc]init];
    [columnsAll addObjectsFromArray:columnsShow];
    [columnsAll addObjectsFromArray:columnsHide];
    //    NSLog(@"%@",columnsAll);
    if (columnsShow.count != 0) { //本地已有数据
        
        columnArray = [[NSMutableArray alloc]init];
        for (int i =0; i<columnsShow.count; i++) {
            NSDictionary *btnDict = [columnsShow objectAtIndex:i];
            [columnArray addObject:[btnDict objectForKey:@"title"]];
        }
        // 更新标题栏
        [self updateColumnScroll];
        
    }else{
        // 请求标题栏数据
        [self requestNewsColumns];
    }
    
    //编辑栏目、栏目排序 加号按钮
    UIButton *change = [UIButton buttonWithType:UIButtonTypeCustom];
    change.frame = CGRectMake(SCREEN_WIDTH-40, 0, 40, 40);
    [change setTitle:@"+" forState:UIControlStateNormal];
    change.backgroundColor = RGBCOLOR(246, 246, 246);
    [change setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    [change addTarget:self action:@selector(changeBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:change];
}
/**
 *  更新标题栏
 */
- (void)updateColumnScroll{
    //清除
    NSMutableArray *deleteArray = [NSMutableArray array];
    for (UIView *view in columnScroll.subviews) {
        if (view.class == [UIButton class]) {
            [deleteArray addObject:view];
        }
    }
    for (UIView *b in deleteArray) {
        [b removeFromSuperview];
    }
    [deleteArray removeAllObjects];
    //添加  设置button的基本信息
    int btnX = 0;
    for (int i = 0 ; i<columnsShow.count; i++) {
        NSString *title = [[columnsShow objectAtIndex:i] valueForKey:@"title"];
        int titleW = title.length * 14;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        btn.frame = CGRectMake(btnX, 0, titleW + 20, 40);
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(columnClick:) forControlEvents:UIControlEventTouchUpInside];
        [columnScroll addSubview:btn];
        btnX += titleW + 20;
    }
    columnScroll.contentSize = CGSizeMake(btnX, 40);
    
    
    // 请求第一个
    if (columnsShow.count > 0) {
        
        // 更新新闻视图（请求新闻数据）
        [self updateScrollView];
    }
}

//选的哪个栏目
-(void)columnClick:(UIButton *)btn{
    [self showListWithIndex:btn.tag];
}
/**
 *   scrollView
 */

//详情内容的scrollview
-(void)creatScrollView{
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-64-40)];
    _scrollView.tag = 1;
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*columnArray.count+1, SCREEN_HEIGHT-64-40);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.backgroundColor = CCOLOR;
    [self.view addSubview:_scrollView];
}


//  更新顶部分类下新闻视图
- (void)updateScrollView{
    //清除
    NSMutableArray *deleteArray = [NSMutableArray array];
    for (UIView *view in _scrollView.subviews) {
        if (view.class == [UITableView class]) {
            [deleteArray addObject:view];
        }
    }
    for (UIView *b in deleteArray) {
        [b removeFromSuperview];
    }
    [deleteArray removeAllObjects];
    [newsData removeAllObjects];
    //添加
    for (int i = 0 ; i<columnsShow.count; i++) {
        //先建数组！！！
        NSMutableArray *news = [NSMutableArray array];
        [newsData addObject:news];
        
        UITableView *tabview = [[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*i, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-40-40) style:UITableViewStylePlain];
        
        MJRefreshNormalHeader *header =
        [[MJRefreshNormalHeader alloc]init];
        header.tag = i;
        [header setRefreshingTarget:self refreshingAction:@selector(refreshWithHeader:)];
        tabview.header = header;
        
        tabview.tag = 1024 + i;
        tabview.delegate = self;
        tabview.dataSource = self;
        tabview.separatorStyle = UITableViewCellSelectionStyleNone;
        [_scrollView addSubview:tabview];
        
        
        // *********** Tiyon *************//
        
        //        _adScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, AdHeight)];
        //
        //        _adScrollView.backgroundColor = [UIColor orangeColor];
        //
        //        tabview.tableHeaderView = _adScrollView;
        
        // *********** Tiyon *************//
        
    }
    //    columnScroll.contentSize = CGSizeMake(SCREEN_WIDTH/5*columnsShow.count, 40);
    //请求第一个
    if (columnsShow.count > 0) {
        [self showListWithIndex:0];
    }
}


//   这个有什么用？？？
//- (void)tabToTop{
//    if (1) {
//        int x = (int)columnScroll.contentOffset.y+20/(int)SCREEN_WIDTH;
//        logdebug(@"%d---",x);
//         UITableView *tab = (UITableView *)[_scrollView viewWithTag:x + 1024];
//
//        [UIView animateWithDuration:0.4 animations:^{
//            tab.scrollsToTop = YES;
//        }];
//    }
//}

#pragma mark - scrolldelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _scrollView) {
        int x = scrollView.contentOffset.x + SCREEN_WIDTH/2;
        int n = x/(int)SCREEN_WIDTH;
        [self showListWithIndex:n];
    }
    if (scrollView == columnScroll) {
        //并木有卵用
    }
}

#pragma mark - tableview

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (newsData.count < 1) {
        return 0;
    }else{
        
        //return [[newsData objectAtIndex:tableView.tag - 1024] count];
        return [[newsData objectAtIndex:tableView.tag - 1024][section]count];
        
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return [[newsData objectAtIndex:tableView.tag - 1024]count];;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
#if new
    
    return 135;
#else
    return 60;
    
#endif
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
#if new
    
    static NSString *identfier = @"cell";
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identfier];
    if (!cell) {
        cell = [[NewsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfier];
        
        
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(10, 34, SCREEN_WIDTH-10, 1)];
        line.layer.borderWidth = 1;
        line.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [cell addSubview:line];
    }
    
    //数据
    if (newsData.count < 1) {
        return cell;
    }
    NSArray *news = [newsData objectAtIndex:tableView.tag - 1024];
    if (news.count <= 0) {
        return cell;
    }
    
    
    NSDictionary * zzdic = [newsData objectAtIndex:tableView.tag - 1024][indexPath.section][indexPath.row];
    
    NSDictionary *dic = [news objectAtIndex:indexPath.section][indexPath.row];
    
    cell.newsImg.image =[UIImage imageNamed:@"5C71F048-5A9A-4A18-A065-8AA2F802E3DD"];
    cell.newsTitle.text = [dic valueForKey:@"title"];
    cell.newsContent.text = [dic valueForKey:@"description"];
    cell.newsDate.text = [GetTime getYYMMDDWithDate:[NSDate dateWithTimeIntervalSince1970:[[dic valueForKey:@"pubdate"] integerValue]]];
    cell.newsRecommend.image = [UIImage imageNamed:@"tuijian"];
    cell.newsHot.image = [UIImage imageNamed:@"remen"];
    if (indexPath.row%3 == 0) {
        cell.newsRecommend.image = nil;
    }
    cell.newsBrowse.text = [NSString stringWithFormat:@"查看%@",[dic valueForKey:@"click"]];
    
    
    
    //    cell.textLabel.text = dic[@"title"];
    NSMutableString *cs = [NSMutableString stringWithFormat:@"%@",dic[@"color"]];
    if ([cs hasPrefix:@"#"]) {
        [cs replaceCharactersInRange:NSMakeRange(0, 1) withString:@"0x"];
    }
    long rgb = strtoul([cs UTF8String], 0, 16);
    logdebug(@"%@",dic[@"color"]);
    cell.textLabel.textColor = UIColorFromRGB(rgb);
    
    //NSLog(@"%@",dic[@"typeid"]);
    
    return cell;
    
    
#else
    
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"newsId"];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"newsId"];
        
        UILabel * lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 58, SCREEN_WIDTH-20, 1)];
        
        lineLabel.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        lineLabel.layer.borderWidth = 1;
        
        [cell addSubview:lineLabel];
        
    }
    
    //数据
    if (newsData.count < 1) {
        return cell;
    }
    NSArray *news = [newsData objectAtIndex:tableView.tag - 1024];
    if (news.count <= 0) {
        return cell;
    }
    
    
    NSDictionary * zzdic = [newsData objectAtIndex:tableView.tag - 1024][indexPath.section][indexPath.row];
    cell.textLabel.numberOfLines = 2;
    cell.textLabel.text = zzdic[@"title"];
    cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
    
    
    return cell ;
    
    
#endif
    
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    
    return @"    ";
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 12;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString *identifier = @"header";
    NewsHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identifier];
    if (!headerView) {
        headerView = [[NewsHeaderView alloc]initWithReuseIdentifier:identifier];
    }
    
    NSArray *news = [newsData objectAtIndex:tableView.tag - 1024];
    NSDictionary *dic = [[news objectAtIndex:section]firstObject];
    headerView.moreBtn.tag = (tableView.tag - 1024)*10000 + [dic[@"typeid"]integerValue];
    [headerView.moreBtn addTarget:self action:@selector(headerMoreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    headerView.titleLabel.text = [NSString stringWithFormat:@"    %@",dic[@"group"]];
    headerView.titleLabel.font = [UIFont systemFontOfSize:20];
    
    return headerView;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 45;
}
/**
 *
 *   点击cell进入资讯详情
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    NSArray *news = [newsData objectAtIndex:tableView.tag - 1024];
    
    // NSDictionary *dic = [news objectAtIndex:indexPath.row];
    NSDictionary *dic = news[indexPath.section][indexPath.row];
    
    NSString *newsid = [NSString stringWithFormat:@"%@",[dic valueForKey:@"id"]];
    NewsContentViewController *vc = [[NewsContentViewController alloc]init];
    vc.title = [columnArray objectAtIndex:tableView.tag - 1024];
    vc.newsid = newsid;
    vc.newsTitle = [dic valueForKey:@"title"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark - request
/**
 *   请求栏目内容
 */
-(void)requestNewsColumns{
    
    NSString *module = @"news";
    NSString *interface = @"columnlist";
    
    NSString *timeString = [GetTime getTime];
    
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    
    
    NSDictionary *parameter = @{@"time":timeString};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        // logdebug(@"%@",dic);
        if ([[dic valueForKey:@"succ"]integerValue] == 1) {
            NSArray *array = [dic valueForKey:@"info"];
            [columnsAll removeAllObjects];
            columnArray = [NSMutableArray array];
            //头条添加
            [columnArray addObject:@"头条"];
            [columnsAll addObject:@{@"title":@"头条",@"id":@"0",@"imgae":@"",@"selectImage":@""}];
            for (int i = 0; i<array.count; i++) {
                NSDictionary *column = [array objectAtIndex:i];
                NSString *title = [column valueForKey:@"typename"];
                //logdebug(@"%@",title);
                NSString *columnid = [NSString stringWithFormat:@"%@",[column valueForKey:@"id"]];
                //                NSLog(@"%@",columnid);
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                                     title,@"title",
                                     columnid,@"id",
                                     @"",@"image",
                                     @"",@"selectImage",
                                     nil];
                [columnArray addObject:title];
                [columnsAll addObject:dic];
            }
            //保存本地并更新
            [columnsAll writeToFile:COMMONLYCOLUMN_PATH atomically:YES];
            columnsShow = [NSMutableArray arrayWithArray:columnsAll];
            columnsHide = [NSMutableArray array];
            [self updateColumnScroll];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //        logdebug(@"%@",error.localizedDescription);
    }];
}


// 下拉刷新
- (void)refreshNewslistWithColumnindex:(NSInteger )index{
    [self requestNewslistWithColumnindex:index andPage:0];
    

}






//  请求分类下列表数据
- (void)requestNewslistWithColumnindex:(NSInteger )index andPage:(int)page{
    NSDictionary *columnDic = [columnsShow objectAtIndex:index];
    NSString *columnid = [NSString stringWithFormat:@"%@",[columnDic valueForKey:@"id"]];
    
    NSString *module = @"news";
    NSString *interface = @"newslist";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    logdebug(@"%@",urlString);
    NSDictionary *parameter;
    if ([columnid isEqualToString:@"0"]) {//无参头条
        parameter = @{@"time":timeString,@"pagecode":[NSString stringWithFormat:@"%d",page]};
    }else{
        parameter = @{@"time":timeString,@"columnid":columnid,@"pagecode":[NSString stringWithFormat:@"%d",page]};
    }
    NSLog(@"%@",parameter);
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    UITableView *tab = (UITableView *)[_scrollView viewWithTag:index + 1024];
    
    
    
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        NSArray *newslist = [dic valueForKey:@"info"];
        
        //logdebug(@"%@",dic);
        // NSLog(@"%@",[self sortArrayWithArray:newslist andKey:@"typeid"]);
        
        
        // logdebug(@"%ld请求完成",(long)index);
        NSMutableArray *news = [newsData objectAtIndex:index];
        if (page == 0) {
            [news removeAllObjects];
        }
        if (newslist.count >= 1) {
            pages[index] += 1;
        }
        
        [news addObjectsFromArray:[self sortArrayWithArray:newslist andKey:@"typeid"]];
        
        
        [tab.header endRefreshing];
        [tab reloadData];
        [hud hide:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        logdebug(@"%@",error.localizedDescription);
        [tab.header endRefreshing];
        [hud hide:YES];
    }];
}

// 将数组中的元素进行分类（根据typeid或group）
- (NSMutableArray *)sortArrayWithArray:(NSArray *)ary andKey:(NSString *)key {
    
    NSMutableArray *dateMutablearray = [@[] mutableCopy];
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:ary];
    
    for (int i = 0; i < ary.count; i++) {
        
        if (array.count > 0) {
            
            
            NSDictionary *dict = array[0];
            
            NSMutableArray *tempArray = [@[] mutableCopy];
            
            [tempArray addObject:dict];
            
            for (int j = 1; j < array.count; j ++) {
                
                NSDictionary *dic = array[j];
                
                if ([dict[key]integerValue] == [dic[key]integerValue]) {
                    
                    [tempArray addObject:dic];
                    
                }
                //            if ([dict[key] isEqualToString:dic[key]]) {
                //
                //                [tempArray addObject:dic];
                //            }
                
            }
            
            [dateMutablearray addObject:tempArray];
            [array removeObjectsInArray:tempArray];
            
        }
    }
    
    return dateMutablearray;
    
}






- (void)refreshWithHeader:(MJRefreshHeader *)header{
    [self refreshNewslistWithColumnindex:header.tag];
}


//- (void)requestMoreWithFooter:(MJRefreshFooter *)footer{
//    [self requestMoreNewslistWithColumnindex:footer.tag];
//}

- (void)showListWithIndex:(NSInteger)index{
    //请求数据
    UITableView *tab = (UITableView *)[_scrollView viewWithTag:index + 1024];
    [tab.header executeRefreshingCallback];
    //内容视图滚
    [UIView animateWithDuration:0.4 animations:^{
        [_scrollView setContentOffset:CGPointMake(index*SCREEN_WIDTH, 0)];
    }];
    //标题视图变化
    int x;
    CGPoint center;
    for (UIView *v in columnScroll.subviews) {
        if (v.class == [UIButton class]) {
            UIButton *btn = (UIButton *)v;
            if (v.tag == index) {
                [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:14];//
                x = btn.frame.origin.x;
                center = btn.center;
            }else{
                [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:12];
            }
        }
    }
    //    logdebug(@"===%f",center.x);
    //标题栏也得滚
    if (center.x > SCREEN_WIDTH/2) {
        if (center.x > columnScroll.contentSize.width - SCREEN_WIDTH/2) {
            [UIView animateWithDuration:0.4 animations:^{
                columnScroll.contentOffset = CGPointMake(columnScroll.contentSize.width - columnScroll.width, 0);
            }];
            return;
        }
        [UIView animateWithDuration:0.4 animations:^{
            columnScroll.contentOffset = CGPointMake(center.x - SCREEN_WIDTH/2, 0);
        }];
    }else{
        [UIView animateWithDuration:0.4 animations:^{
            columnScroll.contentOffset = CGPointMake(0, 0);
        }];
    }
}
/**
 *  显示分类 某类
 *
 *  @param columnid 分类
 *  @param typeid   细分类
 */
- (void)showMoreWithColumnId:(NSString *)columnid andtypeid:(NSString *)typeid andGroup:(NSString *)group{
    NewsTypeViewController *NTVC = [[NewsTypeViewController alloc]init];
    NTVC.columnid = columnid;
    NTVC.newstypeid = typeid;
    NTVC.title = group;
    NTVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:NTVC animated:YES];
}
- (void)headerMoreClick:(UIButton *)btn{
    NSDictionary *columnDic = [columnsShow objectAtIndex:btn.tag/10000];
    NSString *columnid = [NSString stringWithFormat:@"%@",[columnDic valueForKey:@"id"]];
    NSString *typeid = [NSString stringWithFormat:@"%d",btn.tag%10000];
    NSArray *news = [newsData objectAtIndex:btn.tag/10000];
    NSString *vcTitle;
    //    logdebug(@"%@",news);
    for (NSArray *array  in news) {
        for (NSDictionary *dic in array) {
            if ([[dic valueForKey:@"typeid"]integerValue] == [typeid integerValue]) {
                vcTitle = [dic valueForKey:@"group"];
                break;
            }
        }
        if (vcTitle.length >0) {
            break;
        }
    }
    
    [self showMoreWithColumnId:columnid andtypeid:typeid andGroup:vcTitle];
}
/**
 *   改变栏目，编辑栏目
 */
- (void)changeBtn{
    ChangeNewsViewController *vc = [[ChangeNewsViewController alloc]init];
    //logdebug(@"%@",columnsShow);
    vc.inArray = columnsShow;
    vc.outArray = columnsHide;
    //TODO:使用本地文件读写也可以，block返回参数也可以，毕竟进入初始化的时候是读取的本地文件，偏向于读取本地文件
    //block
    vc.newsBlock = ^(NSMutableArray *inA,NSMutableArray *outA){
        _scrollView.contentOffset = CGPointMake(0,0);
        columnArray = [[NSMutableArray alloc]init];
        for (int i =0; i<inA.count; i++) {
            NSDictionary *btnDict = [inA objectAtIndex:i];
            [columnArray addObject:[btnDict objectForKey:@"title"]];
        }
        columnsShow = [NSMutableArray arrayWithArray:inA];
        columnsHide = [NSMutableArray arrayWithArray:outA];
        [columnsShow writeToFile:COMMONLYCOLUMN_PATH atomically:YES],
        [columnsHide writeToFile:OTHERCOLUMN_PATH atomically:YES];
        [self updateColumnScroll];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

@end
